package com.yz.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yz.common.R;
import com.yz.entity.ShoppingCart;
import com.yz.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
@Slf4j
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 获取购物车列表数据
     * @param session
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> list = shoppingCartService.list(wrapper);
        return R.success(list);
    }

    /**
     * 添加至购物车
     * @param shoppingCart
     * @param session
     * @return
     */
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart, HttpSession session){
        log.info("ShoppingCart:{}",shoppingCart);

        // 添加 ShoppingCart 中缺少的数据
        Long userId = (Long) session.getAttribute("user");
        shoppingCart.setUserId(userId);

        // 查询 shopping_cart表 中是否已经存在该数据 存在数量+1  不存在则保存为一条新数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(shoppingCart.getDishId() != null, ShoppingCart::getDishId,shoppingCart.getDishId());
        wrapper.eq(shoppingCart.getSetmealId() != null, ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        ShoppingCart one = shoppingCartService.getOne(wrapper);
        if(one != null){
            // 存在  数量 + 1
            one.setNumber(one.getNumber()+1);
            shoppingCartService.updateById(one);
            shoppingCart = one;
        }else{
            // 不存在  数量 = 1
            shoppingCart.setNumber(1);
            shoppingCartService.save(shoppingCart);
        }
        return R.success(shoppingCart);
    }
}
